package com.neutech.service.impl;

import com.neutech.dao.CartDAO;
import com.neutech.dao.FoodDAO;
import com.neutech.dao.impl.CartDAOImpl;
import com.neutech.dao.impl.FoodDAOImpl;
import com.neutech.entity.Cart;
import com.neutech.entity.Food;
import com.neutech.service.CartService;
import com.neutech.vo.ResultVO;

public class CartServiceImpl implements CartService {

    private FoodDAO foodDAO = new FoodDAOImpl();

    private CartDAO cartDAO  = new CartDAOImpl();
    @Override
    public ResultVO add(Integer foodId, Integer quantity, Integer userId) {
        Food food = foodDAO.getById(foodId);
        if (food == null) {
            return ResultVO.error(4001,"数据不合法");
        }

        Cart cartData = cartDAO.getByFoodIdAndUserId(foodId,userId);
        if (cartData == null) {
            Cart cart = new Cart();
            cart.setFoodId(food.getId());
            cart.setFoodName(food.getFoodName());
            cart.setFoodImg(food.getFoodImg());
            cart.setFoodPrice(food.getFoodPrice());
            cart.setBusinessId(food.getBusinessId());
            cart.setUserId(userId);
            cart.setQuantity(quantity);
            cartDAO.add(cart);
        } else {
            cartData.setQuantity(cartData.getQuantity() + quantity);
            cartDAO.updateQuantity(cartData);
        }
        return ResultVO.success();
    }

    @Override
    public ResultVO listCartByUserId(Integer userId) {
        return ResultVO.success(cartDAO.listByUserId(userId));
    }

    @Override
    public ResultVO updateQuantityById(Integer id, Integer quantity, Integer userId) {
        Cart cart = cartDAO.getByAndUserId(id,userId);
        if (cart == null) {
            return ResultVO.error(1005,"数据不合法");
        }
        cart.setQuantity(quantity);

        cartDAO.updateQuantity(cart);
        return ResultVO.success();
    }

    @Override
    public ResultVO deleteByQuantity(Integer userId) {
        if (userId==null){
            ResultVO.error(3003,"数据不合法");
        }
        return ResultVO.success(cartDAO.deleteByQuantity());
    }
}
